<script setup>
import {ref,watch,onMounted} from 'vue'
import {queryEmpApi,addEmpApi,getByIdApi,updateApi,deleteByIdApi} from '@/api/emp.js'
import {Delete,Edit,} from '@element-plus/icons-vue'
import {queryAllApi} from '@/api/dept.js'
import { ElMessage,ElMessageBox } from 'element-plus';


//令牌token
let token=ref('');
//获取token
let getToken=()=>{
  let loginUserStr=localStorage.getItem('loginUser');
  if (loginUserStr) {
    token.value=JSON.parse(loginUserStr).token;
  }
}


//定义基础数据
//职位列表数据
const jobs = ref([{ name: '班主任', value: 1 },{ name: '讲师', value: 2 },{ name: '学工主管', value: 3 },{ name: '教研主管', value: 4 },{ name: '咨询师', value: 5 },{ name: '其他', value: 6 }])
//性别列表数据
const genders = ref([{ name: '男', value: 1 }, { name: '女', value: 2 }]);
//部门列表数据
const depts = ref([]);
let empList=ref([])
//员工查询的数据
let emp=ref({
  name:'',
  gender:'',
  date:[],
  begin:'',
  end:''
})
//watch侦听
watch(()=>emp.value.date,(newval,iloval)=>{
  if(emp.value.date &&emp.value.date.length>0){
    emp.value.begin=emp.value.date[0];
    emp.value.end=emp.value.date[1];
  }
})
// 查询部门
let selectdepts=async()=>{
  let result=await queryAllApi();
  if (result.code) {
    depts.value=result.data;
  }
}
// 查询员工
let select=async()=>{
    let result=await queryEmpApi(emp.value.name,
                                emp.value.gender,
                                emp.value.begin,
                                emp.value.end,
                                page.value,
                                pageSize.value
    ); 
    if (result.code) {
      empList.value=result.data.rows;
      total.value=result.data.total;
    }
}
//清空方法
let clear=()=>{
  emp.value={name:'',gender:'',date:[],begin:'',end:''}
  select();
}

//钩子函数加载就执行
onMounted(() => {
  select();
  selectdepts();
  getToken();
})
// 分页
let page=ref(1)
let pageSize=ref(10)
let total=ref(0)
//分页一点就查询
const handleSizeChange = (val) => {
  select();
}
const handleCurrentChange = (val) => {
  select();
}

//新增/修改表单
const employee = ref({
  username: '',
  name: '',
  gender: '',
  phone: '',
  job: '',
  salary: '',
  deptId: '',
  entryDate: '',
  image: '',
  exprList: []
})

// 控制弹窗
const dialogVisible = ref(false)
const dialogTitle = ref('')
//
let add=()=>{
  dialogVisible.value=true;
  dialogTitle.value='新增员工'
  //清空表单
  employee.value = {
    username: '',
    name: '',
    gender: '',
    phone: '',
    job: '',
    salary: '',
    deptId: '',
    entryDate: '',
    image: '',
    exprList: []
  }
  //清空校验信息
  if(empFormRef.value){
    empFormRef.value.resetFields();
  }
}

//文件上传
// 图片上传成功后触发
const handleAvatarSuccess = (response) => {
  employee.value.image=response.data;
}
// 文件上传之前触发
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('只支持上传图片')
    return false
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('只能上传10M以内图片')
    return false
  }
  return true
}
//员工经历
let addexpr=()=>{
  employee.value.exprList.push({company:'',job:'',begin:'',end:'',exprData:[]})//看接口文档员工经历需要传递的参数
}
//动态删除员工经历
let deleteexpr=(index)=>{
  employee.value.exprList.splice(index,1)//根据employee对象中的数组exprList索引来删除
}
//侦听empxpr数组中的对象的数组exprDate
watch(()=>employee.value.exprList,(newVal,oldVal)=> {
  if (employee.value.exprList&&employee.value.exprList.length>0) {//如果employee属性值中的exprList存在并且长度不为零执行以下代码
    employee.value.exprList.forEach(expr=>{//expr是遍历出来的每一个属性的值
      if (expr.exprData&&expr.exprData.length>0) {//如果expr中的exprData数组有且不为零
        expr.begin=expr.exprData[0]
        expr.end=expr.exprData[1]
      }
    })
  }
},{deep:true})//深度侦听
//保存员工
let addEmp=async()=>{
   //保存之前, 先校验表单, 校验通过, 再发送请求
   if (!empFormRef) return
  await empFormRef.value.validate(async(valid, fields) => {
    if (valid) { //通过
      let result;
      if (employee.value.id) {
        result=await updateApi(employee.value)
        dialogVisible.value = false;
      }else{
        result = await addEmpApi(employee.value);
        dialogVisible.value = false;
      }
      
      if(result.code){//成功
        dialogVisible.value = false;
        ElMessage.success('保存成功');
        search();
      }else {
        ElMessage.error(result.msg);
      }

    } else { //不通过
      ElMessage.error('表单校验不通过,请检查表单');
    }
  })
}
//表单校验规则
//表单校验
const empFormRef = ref();
//表单校验规则
const rules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度应在2到20个字符之间', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度应在2到10个字符之间', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' } //正则表达式 : ^ 开头，$ 结尾, \d 匹配数字
  ]
});
//查询回显
let updateEmp=async(id)=>{
  dialogVisible.value=true;
  let result=await getByIdApi(id);
  console.log(result);
  employee.value=result.data
  employee.value.exprList.value;
  if (employee.value.exprList&&employee.value.exprList.length>0) {
    employee.value.exprList.forEach(expr=>{
      expr.exprData=[expr.begin,expr.end]
    })
  }
  dialogTitle.value='修改员工'
  if (empFormRef.value) {
    empFormRef.value.resetFields();
  }
}

//单个删除员工
const deleteEmp=(id)=>{
  //console.log(id);
  ElMessageBox.confirm('您确定要删除部门吗?','警告',
    {confirmButtonText: '确认',cancelButtonText: '取消',type: 'warning',}
  ).then(async() => {//确认
      const result = await deleteByIdApi(id);
      if(result.code){
        ElMessage.success('删除成功');
        select();
      }else{
        ElMessage.error(result.message);
      }
    }).catch((err) => {//失败回调
      console.log(err)
      ElMessage.info("操作取消")
      })
}
//批量删除员工
let ids=ref([])
let handleSelectionChange=(array)=>{
  ids.value=array.map(item=>item.id)
  //ids.value=array.map(item=> item.id)//return和大括号可以省略
}

let deleteById=()=>{
  ElMessageBox.confirm('您确定要删除部门吗?','警告',
    {confirmButtonText: '确认',cancelButtonText: '取消',type: 'warning',}
  ).then(async() => {//确认
      const result = await deleteByIdApi(ids.value);
      if(result.code){
        ElMessage.success('删除成功');
        select();
      }else{
        ElMessage.error(result.message);
      }
    }).catch((err) => {//失败回调
      console.log(err)
      ElMessage.info("操作取消")
      })
}



</script>

<template>
  <h1>员工管理</h1>
  <!-- 查询的表单 -->
  <div id="cd">
    <!-- {{ emp }} -->
      
  <el-form :inline="true" :model="emp" class="demo-form-inline" >
    <el-form-item label="姓名">       <!--{{ ids }}-->
      <el-input v-model="emp.name" placeholder="请输入姓名" />
    </el-form-item>
    <el-form-item label="性别">
      <el-select
        v-model="emp.gender"
        placeholder="请选择性别">
        <el-option label="男" value="1" />
        <el-option label="女" value="2" />
      </el-select>
    </el-form-item>
    <el-form-item label="请选择日期">
      <el-date-picker
      v-model="emp.date"
        type="daterange"
        range-separator="到"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="YYYY-MM-DD"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="select">查询</el-button>
      <el-button type="danger" @click="clear">清空</el-button>
    </el-form-item>
  </el-form>
</div>
<!-- 新增员工和批量删除 按钮-->
 <div id="dd">
<el-button type="primary" @click="add"><el-icon><Plus /></el-icon>新增员工</el-button>
<el-button type="danger" @click="deleteById"><el-icon><WarningFilled /></el-icon>批量删除</el-button>

</div>
<!-- 展示内容的表格 -->
<el-table
    ref="multipleTableRef"
    :data="empList"
    style="width: 100%"
    @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection" :selectable="selectable" width="55" />
    <el-table-column property="name" label="姓名" width="120" />
    <el-table-column property="gender" label="性别">
      <template #default="scope">
        {{ scope.row.gender==1? '男':'女' }}
      </template>
    </el-table-column>
    <el-table-column property="image" label="头像">
      <template #default="scope">
        <img :src="scope.row.image" height="50px" >
      </template>
    </el-table-column>
    <el-table-column property="deptName" label="所属部门" />
    <el-table-column property="job" label="职位" >
      <template #default="scope">
        <span v-if="scope.row.job==1">班主任</span>
        <span v-else-if="scope.row.job==2">讲师</span>
        <span v-else-if="scope.row.job==3">学工主管</span>
        <span v-else-if="scope.row.job==4">教研主管</span>
        <span v-else-if="scope.row.job==5">咨询师</span>
        <span v-else>其他</span>
      </template>
    </el-table-column>
    <el-table-column property="createTime" label="入职时间" />
    <el-table-column property="updateTime" label="最后操作时间" />
    <el-table-column  label="操作">
      <template #default="scope">
      <el-button type="warning" @click="updateEmp(scope.row.id)" :icon="Edit"  circle/>
      <el-button type="danger" @click="deleteEmp(scope.row.id)" :icon="Delete"  circle/>
    </template>
    </el-table-column>
  </el-table>
  <!-- 分页 -->
  <div class="demo-pagination-block">
    <div class="demonstration">
    <el-pagination
      v-model:current-page=page
      v-model:page-size=pageSize
      :background="background"
      :page-sizes="[10, 20, 30, 40]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    </div>
  </div>

   <!-- 新增/修改员工的对话框 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle" >
      <el-form :model="employee" label-width="80px" :rules="rules" ref="empFormRef">
        <!-- 基本信息 -->
        <!-- 第一行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="employee.username" placeholder="请输入员工用户名，2-20个字"></el-input>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="employee.name" placeholder="请输入员工姓名，2-10个字"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="employee.gender" placeholder="请选择性别" style="width: 100%;">
                <el-option v-for="gender in genders" :label="gender.name" :value="gender.value" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="employee.phone" placeholder="请输入员工手机号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="职位">
              <el-select v-model="employee.job" placeholder="请选择职位" style="width: 100%;">
                <el-option v-for="job in jobs" :label="job.name" :value="job.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="薪资">
              <el-input v-model="employee.salary" placeholder="请输入员工薪资"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第四行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属部门">
              <el-select v-model="employee.deptId" placeholder="请选择部门" style="width: 100%;">
                <el-option v-for="dept in depts" :label="dept.name" :value="dept.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入职日期">
              <el-date-picker v-model="employee.entryDate" type="date" style="width: 100%;" placeholder="选择日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第五行 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="头像">
              <el-upload
                class="avatar-uploader"
                action="/api/upload"
                :headers="{'token':token}"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                >
                <img v-if="employee.image" :src="employee.image" class="avatar" width="50px"/>
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        

        <!-- 工作经历 -->
        <!-- 第六行 -->
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="工作经历">
              <el-button type="success" size="small" @click="addexpr">+ 添加工作经历</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 第七行 ...  工作经历 -->
        <el-row :gutter="3" v-for="(expr, index) in employee.exprList" >
          <el-col :span="10">
            <el-form-item size="small" label="时间" label-width="80px">
              <el-date-picker v-model="expr.exprData" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" ></el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item size="small" label="公司" label-width="60px">
              <el-input v-model="expr.company" placeholder="请输入公司名称"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item size="small" label="职位" label-width="60px">
              <el-input v-model="expr.job" placeholder="请输入职位"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="2">
            <el-form-item size="small" label-width="0px">
              <el-button type="danger" @click="deleteexpr(index)" >- 删除</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <!-- 底部按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addEmp">保存</el-button>
        </span>
      </template>
  </el-dialog>
  
</template>

<style scoped>
#dd{
  margin-bottom: 20px;
}
#cd {
margin: 20px 0px;
}
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>